package com.jacky.webflux.controllers;

import com.jacky.webflux.commons.BasicResp;
import com.jacky.webflux.dtos.AppUserDto;
import com.jacky.webflux.exceptions.BusinessException;
import com.jacky.webflux.services.AppUserService;
import jakarta.annotation.Resource;
import org.springframework.web.bind.annotation.*;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;

@RestController
@RequestMapping("appUser")
public class AppUserController {

    @Resource
    private AppUserService appUserService;

    @GetMapping("/get/{userId}")
    Mono<AppUserDto> getAppUser(@PathVariable("userId") Long userId) {
        return appUserService.getById(userId);
    }

    @PostMapping("/save")
    Mono<AppUserDto> saveUser(@RequestBody AppUserDto dto) {
        return appUserService.saveUser(dto);
    }

    @PutMapping("/update/{userId}")
    Mono<AppUserDto> updateUser(@PathVariable("userId") Long userId, @RequestBody AppUserDto dto) {
        return appUserService.updateById(userId, dto);
    }

    @GetMapping("/delete/{userId}")
    Mono<Void> deleteAppUser(@PathVariable("userId") Long userId) {
        return appUserService.deleteById(userId);
    }

    @GetMapping("/getAll")
    Flux<AppUserDto> getAll() {
        return appUserService.getAllUsers();
    }

    @GetMapping("/businessException/{userId}")
    Mono<AppUserDto> businessException(@PathVariable("userId") Long userId) {
        if (userId <= 0) throw new BusinessException(301, "cause business exception");
        return appUserService.getById(userId);
    }


    /**
     * 针对AppUserController类抛出的NullPointerException类型异常进行捕获
     *
     * @param e
     * @return
     */
    @ExceptionHandler({BusinessException.class})
    Mono<BasicResp<String>> exceptionHandle(BusinessException e) {
        return Mono.just(BasicResp.fail(e.getCode(), e.getMessage()));
    }
}
